package com.zdj.data.net;

import android.content.Context;

import com.zdj.utils.MyLogUtil;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by zdj on 16-12-10.
 */

public class CacheInterceptor implements Interceptor {

    private Context mContext;

    public CacheInterceptor(Context context) {
        mContext = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request newRequest ;

        if(NetUtils.isNetworkAvailable(mContext)){
            newRequest  = chain.request().newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();
        }else {
            newRequest  = chain.request().newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        }

        Response originResponse = chain.proceed(newRequest);
        Response cache = originResponse.cacheResponse();
        Response netRes = originResponse.networkResponse();
        MyLogUtil.d("CacheInterceptor", "intercept: \n" + "缓存:" + cache);
        MyLogUtil.d("CacheInterceptor", "intercept: \n" + "网络:" + netRes);

        // 设置缓存时间未 60s ,移除消息头pragma(控制缓存)
        return originResponse.newBuilder().removeHeader("Pragma").addHeader("Cache-Control","public,max-age=60").build();
    }
}
